/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.service.datasource;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import yhao.infra.common.model.Entity;
import yhao.infra.common.util.CommonListUtil;
import yhao.infra.service.ServiceBaseConfig;
import yhao.infra.service.YhaoInfraServiceProperties;
import yhao.infra.service.datasource.mybatis.dialect.Dialect;
import yhao.infra.service.datasource.mybatis.interceptor.BaseInterceptor;
import yhao.infra.service.datasource.mybatis.interceptor.PaginationInterceptor;
import yhao.infra.service.datasource.mybatis.interceptor.SqlStatInterceptor;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ScheduledExecutorService;

/**
 * Dao 通用配置工厂
 * <ul>
 *     <li>sqlSession配置定义</li>
 * </ul>
 *
 * @author yoara
 */
public class BaseDaoConfigFactory {

    public static SqlSessionFactory makeSqlSessionFactory(YhaoInfraServiceProperties baseProperties,
                  DataSource dataSource, Class<? extends Dialect> type) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        VFS.addImplClass(SpringBootVFS.class);

        Configuration configuration = baseProperties.getMybatis().getConfiguration();
        if (configuration == null) {
            configuration = new Configuration();
        }
        bean.setConfiguration(configuration);
        if (baseProperties.getMybatis().getConfigurationProperties() != null) {
            bean.setConfigurationProperties(baseProperties.getMybatis().getConfigurationProperties());
        }
        //框架拦截器
        BaseInterceptor baseInterceptor = new BaseInterceptor();

        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        Properties pageProperties = new Properties();
        pageProperties.setProperty(PaginationInterceptor.DIALECT_CLASS_PROPERTY, type.getName());
        paginationInterceptor.setProperties(pageProperties);

        List<Interceptor> pluginList =
                CommonListUtil.NEW(baseInterceptor,paginationInterceptor);
        if(baseProperties.getMybatis().isStatSql()){
            SqlStatInterceptor.turnOn();
            pluginList.add(new SqlStatInterceptor());
        }
        if(CommonListUtil.isNotEmpty(ServiceBaseConfig.getCustomizeMybatisInterceptors())){
            pluginList.addAll(ServiceBaseConfig.getCustomizeMybatisInterceptors());
        }
        bean.setPlugins(pluginList.toArray(new Interceptor[]{}));

        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage(baseProperties.getMybatis().getAliasesPackage());
        bean.setTypeAliasesSuperType(Entity.class);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setMapperLocations(resolver.getResources(baseProperties.getMybatis().getMapperLocation()));

        SqlSessionFactory factory = bean.getObject();
        return factory;
    }

    protected static DruidDataSource makeDruidDataSource(
            BaseDaoSqlProperties properties,
            ScheduledExecutorService createScheduler,ScheduledExecutorService destroyScheduler) {
        DruidDataSource source = new DruidDataSource();

        source.setUrl(properties.getUrl());
        source.setUsername(properties.getUsername());
        source.setPassword(properties.getPassword());
        source.setInitialSize(properties.getDruidInitialSize());
        source.setMinIdle(properties.getDruidMinIdle());
        source.setMaxActive(properties.getDruidMaxActive());
        source.setMaxWait(properties.getDruidMaxWait());
        source.setTimeBetweenEvictionRunsMillis(properties.getDruidTimeBetweenEvictionRunsMillis());
        source.setMinEvictableIdleTimeMillis(properties.getDruidMinEvictableIdleTimeMillis());
        source.setPoolPreparedStatements(properties.isDruidPoolPreparedStatements());

        //配置Filter
        List<Filter> filterList = new ArrayList<>();
        if(properties.getDruidStat().isEnable()){
            StatFilter statFilter = new StatFilter();
            statFilter.setMergeSql(properties.getDruidStat().isDruidStatMergeSql());
            statFilter.setSlowSqlMillis(properties.getDruidStat().getDruidStatSlowSqlMillis());
            statFilter.setLogSlowSql(properties.getDruidStat().isDruidStatLogSlowSql());
            filterList.add(statFilter);
        }
        if(CommonListUtil.isNotEmpty(filterList)){
            source.setProxyFilters(filterList);
        }

        //配置开启连接泄漏检测
        if(properties.getAbandoned().isEnable()){
            source.setRemoveAbandoned(true);
            source.setRemoveAbandonedTimeout(properties.getAbandoned().getRemoveAbandonedTimeout());
            source.setLogAbandoned(properties.getAbandoned().isLogAbandoned());
        }

        //配置其他参数
        source.setConnectProperties(properties.getAdditionalProperties());

        source.setCreateScheduler(createScheduler);
        source.setDestroyScheduler(destroyScheduler);
        return source;
    }
}
